package com.jfplugin.je;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.plugin.IPlugin;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;

/**
 * BDB插件
 * @author farmer
 */
public class BerkeleyDbPlugin implements IPlugin{

	/**
	 * bdbPluginMap
	 */
	static final Map<String, BerkeleyDbPlugin> bdbPluginMap = new HashMap<String, BerkeleyDbPlugin>();
	
	Environment env = null;
	/**
	 * 
	 */
	private EnvironmentConfig envConfig = null;
	/**
	 * 
	 */
	DatabaseConfig dbConfig = null;
	
	private String envHome = null;
	
	public final static String DEFAULTCONFIGNAME = "MAIN";
	
	private String configName = DEFAULTCONFIGNAME;
	
	boolean tx = false;
	
	public BerkeleyDbPlugin(String envHome){
		this(DEFAULTCONFIGNAME,envHome, false);
	}

	public BerkeleyDbPlugin(String envHome , boolean tx){
		this(DEFAULTCONFIGNAME, envHome, tx);
	}
	
	public BerkeleyDbPlugin(String configName,String envHome) {
		this(configName, envHome, false);
	}
	
	public BerkeleyDbPlugin(String configName,String envHome,boolean tx) {
		this.configName = configName;
		this.envHome = envHome;
		this.tx = tx;
	}
	
	@Override
	public boolean start() {
		envConfig = new EnvironmentConfig();
		envConfig.setAllowCreate(true);
		envConfig.setTransactional(tx);
		envConfig.setLocking(tx);
		dbConfig = new DatabaseConfig();
	    dbConfig.setAllowCreate(true);
	    dbConfig.setTransactional(tx);
	    dbConfig.setDeferredWrite(!tx);
		File envDir = new File(envHome);
		if(!envDir.exists()){
			envDir.mkdirs();
		}
	    env = new Environment(envDir, envConfig);
	    bdbPluginMap.put(configName, this);
	    BerkeleyDbKit.init();
		return true;
	}

	@Override
	public boolean stop() {
		BerkeleyDbKit.closeAll();
		env.close();
		return true;
	}

}
